<?php

/**
 * 云仓RPC消息服务中心
 */
namespace App\Service\RpcService;
use App\Service\Code\Normal;
use App\Service\BaseService;
use Hyperf\Task\Annotation\Task;
use App\Model\PssLogModel\RpcMicroServiceLog;
use Service\AppService\IdService;
class YunCangRpcService extends BaseService
{
    /**
     * 接收消息进入对应服务层
     * @param array $arguments
     */
    public function receive( array $message = [] )
    {
        if ( empty($message['method']) ) {
            return Normal::returnCode(Normal::FAIL,"method不能为空");
        }
        
        if ( !isset($message['argments']) ) {
            return Normal::returnCode(Normal::FAIL,"argments缺失");
        }
        
        $req_used_time = microtime(true);
        $result = $this->startAsyncTaskConsumer($message);
        //返回错误的时候才写入日志
        if( $result['code'] != Normal::SUC ) {
            $logParameters = [
                'id'                => IdService::instance()->getOtherID(),
                'interface_code'    => $message['method'],
                'request_url'       => '0.0.0.0',
                'request_param'     => json_encode($message,JSON_UNESCAPED_UNICODE),
                'response_code'     => $result['code'] ?? 0,
                'response_data'     => json_encode($result,JSON_UNESCAPED_UNICODE),
                'req_used_time'     => bcsub((string)microtime(true), $req_used_time,3),
            ];
            RpcMicroServiceLog::instance()->insert($logParameters);
        }
        return $result;
    }
    
    /**
     * #Task()
     * 开始异步task消费队列
     * @param array $message
     */
    public function startAsyncTaskConsumer( array $message = [] )
    {
        try {
            $interface_code         = $message['method'];
            $requestMethodsModule   = \explode(".",$interface_code);
            //解析模块容器
            $service = $requestMethodsModule[0];
            $class   = $requestMethodsModule[1];
            $method  = $requestMethodsModule[2];
            //解析数据
            $argments       = $message['argments'];
            $classService   = "App\\Service\\{$service}\\{$class}";
            $object         = container()->get($classService);
            return $object->{$method}($argments);
        } catch ( \Throwable $th) {
            return Normal::returnCode(Normal::INNER_ERROR,"内部错误",[
                'errorMsg'  => $th->getMessage(),
                'errorFile' => $th->getFile(),
                'errorLine' => $th->getLine(),
            ]);
        }
    }
}